package com.example.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lbq
 * @date 2021/11/24 21:14
 */
public class DataSourceConfig {

    public final static String URL = "url";
    public final static String CLASS_NAME = "className";
    public final static String USERNAME = "username";
    public final static String PASSWORD = "password";

    private static DruidDataSource dataSource;

    private DataSourceConfig() {
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 初始化连接池信息
     */
    public static void init() {

        final ZkClient zkClient = new ZkClient("node2:2181");
        zkClient.createPersistent("/datasource", true);
        Map<String, String> map = new HashMap<>();
        map.put(URL, "jdbc:mysql://127.0.0.1:3306/lagou_study?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true");
        map.put(CLASS_NAME, "com.mysql.jdbc.Driver");
        map.put(USERNAME, "root");
        map.put(PASSWORD, "root");
        zkClient.writeData("/datasource", JSONObject.toJSONString(map));
        dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/lagou_study?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("root");

        zkClient.subscribeDataChanges("/datasource", new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) {
                Map<String, String> newMap = JSONObject.parseObject(data.toString(), Map.class);
                System.out.println(newMap.get(URL));
                System.out.println(newMap.get(CLASS_NAME));
                System.out.println(newMap.get(USERNAME));
                System.out.println(newMap.get(PASSWORD));
                dataSource = new DruidDataSource();
                dataSource.setUrl(newMap.get(URL));
                dataSource.setDriverClassName(newMap.get(CLASS_NAME));
                dataSource.setUsername(newMap.get(USERNAME));
                dataSource.setPassword(newMap.get(PASSWORD));
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {

            }
        });

    }
}
